package com.mlt.gwt.test.server;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;
import org.hibernate.Session;

import com.mlt.gwt.test.server.domain.Appuntamento;

public class AppuntamentoDao {
	static ArrayList<Appuntamento> lst = new ArrayList<Appuntamento>();
	protected Session session_hd;
	protected Session session_usb;
	protected AppuntamentiManager mgr = new AppuntamentiManager();
	
	private Session getSession(Appuntamento event) {
		if(event != null)
			return getSession(event.isPrivate());
		else
			return getSession(false);
	}
	
	private Session getSession(boolean isPrivate) {
		if(isPrivate) {
			return HibernateUtil.getSession_usb();
		}
		else {
			return HibernateUtil.getSession_hd();
		}
		
	}
	
	public Appuntamento save(Appuntamento appuntamento) {
		Session session = getSession(appuntamento);
		
		session.beginTransaction();

		session.save(appuntamento);
		session.getTransaction().commit();
		lst.add(appuntamento);
		System.out.println("Server Saved2 " + lst.size());
		return appuntamento;
	}

	public Appuntamento findById(Long id) {
		System.out.println("Server Find " + id);
		return null;
	}

	public int count() {
		System.out.println("Server cnt = " + lst.size());
		return lst.size();
	}

	public void reset() {
		System.out.println("Server reset ");
		lst.clear();
	}

	public List<Appuntamento> getAppuntamenti(int startIndex, int maxCount) {
		lst.clear();
		System.out.println("Server getEvents " + startIndex);

		//  datastore pubblico
		Session s1 = getSession(false);
		s1.beginTransaction();
			List lstPublic = s1.createQuery("Select a from Appuntamento a").list();
			lst.addAll(lstPublic);
		s1.getTransaction().commit();

		//  datastore privato
		Session s2 = getSession(true);
		s2.beginTransaction();
			List lstPrivate = s2.createQuery("Select a from Appuntamento a").list();
			lst.addAll(lstPrivate);
		s2.getTransaction().commit();
		
		int end = Math.min(startIndex + maxCount, lst.size());
	      if (startIndex == end) {
	        return Collections.emptyList();
	      }
		return lst.subList(startIndex, end);
	}
	
	public List<Appuntamento> findByName(String name) {
		System.out.println("Server Find by Name " + name);
		return lst;
	}

}
